<?php
/***************************************************************************
 * @Description: 内容模型
 * 
 * @FileName:         ContentModel.php
 * @Author :          liyong5@staff.sina.com.cn
 * @CreatedTime:      Tue 29 May 2018 10:10:38 AM CST
 ************************************************************************/

namespace app\modules\core\models;

use Yii;
use yii\base\InvalidArgumentException;
use yii\mongodb\ActiveRecord;
use MongoDB\Bson\ObjectID;
use app\modules\core\models\Validator;

class Model extends ActiveRecord
{
    private $fieldSet;

    private $fieldAttrs;

    /**
     * @inheritdoc
     */
    public static function collectionName()
    {
        return 'model';
    }

    /**
     * @inheritdoc
     */
    public function attributes()
    {
        return ['_id', 'id', 'modelName', 'desc', 'refCount', 'fields', 'fcount', 'refList'];
    }

    public function attributeLabels() {
        return [
            'id'    => 'ID',
            'modelName'  => '模型名',
            'desc'  => '模型描述',
        ];
    }

    /**
     * @inheritdoc
     */
    public function formName() {
        return '';
    }

    /**
     * @inheric
     */
    public function rules() {
        return [
            [['modelName', 'desc', 'fields', 'fcount'], 'required'],
            ['modelName', 'match', 'pattern' => '/[a-zA-Z0-9_-]{6,20}/'],
            ['fields', 'validateFields'],
        ];
    }

    public function validateFields() {
    }

    public function getFieldSet() {
        return $this->fieldSet ? $this->fieldSet : [];
    }

    public function fillFields() {
        if (empty($this->fields)) {
            return true;
        }

        $fieldIds = array_map(function ($id){
                        return new ObjectID($id);
                        }, $this->fields);

        $fields = Field::find()
                ->where(['_id' => ['$in' => $fieldIds]])
                ->all();

        foreach ($fields as $field) {
            $field['widget'] = $this->view2widget($field['view']);

            // 合并验证器属性

            $this->fieldSet[strval($field['_id'])] = $field;

            $this->fieldAttrs[] = $field['id'];
        }
        return $this;
    }

    private function view2widget($view) {
        if (empty($view)) {
            return "testInput";
        }
        $words = array_map('ucFirst', explode('-', $view));

        return lcfirst(implode($words));
    }

    public function getFieldAttrs() {
        return $this->fieldAttrs;
    }

    // 通过一个固定的码表生成惟一id
    public function genId() {
        $codeTable = "ABCDEFJHIJKLMNOPQRstuvwxyzabcdefjhijklmnopqrSTUVWXYZ0123456789";

        $yearCode = $codeTable[intval(date('y'))];
        $monthCode = $codeTable[intval(date('m'))];
        $dayCode = $codeTable[intval(date('d'))];
        $hourCode = $codeTable[intval(date('H'))];
        $minuteCode = $codeTable[intval(date('i'))];
        $secodeCode = $codeTable[intval(date('s'))];

        $microSecod = substr(microtime(), 2, 2);
        return $yearCode . $monthCode . $dayCode . $hourCode . $minuteCode . $secodeCode . $microSecod;
    }

    public function genLables() {
        $lables = [];
        foreach ($this->fieldSet as $key => $value) {
            $lables[$value['id']] = $value['name'];
        }
        return $lables;
    }

    public function genRules() {
        $rules = [];

        $validators = Validator::find()
            ->where(['enable' => '1'])
            ->all();
        foreach ($validators as $key => $validator) {
            $validators[$validator['id']] = $validator;
            unset($validators[$key]);
        }

        foreach ($this->fieldSet as $id => $field) {
            if ($field->required) {
                $rules[] = [$field->id, 'required'];
            }

            if (! isset($field->validates) || empty($field->validates)) {
                continue;
            }

            foreach ($field->validates as $id) {
                if (isset($validators[$id])) {
                    $rules[] = array_merge([$field->id, $validators[$id]->ns],
                        json_decode($validators[$id]->params, true));
                }
            }
        }

        return $rules;
    }
}
